package com.lgy.controller;

import com.lgy.beans.ProductCategory;
import com.lgy.beans.ProductInfo;
import com.lgy.exception.SellException;
import com.lgy.service.ProductCategoryService;
import com.lgy.service.ProductService;
import com.lgy.vo.ProductInfoVO;
import com.lgy.vo.ProductVO;
import com.lgy.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("buyer/product")
public class BuyerProductController extends BaseController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService categoryService;

    @GetMapping("/list")
//    @Cacheable(cacheNames = "product", key = "123")
    public ResultVO list() throws SellException {
        // 查询所有上架商品
        List<ProductInfo> productInfoList = productService.findUpAll();
        // 查询类目(一次性查询)
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(
                productInfoList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList()));
        // 数据封装
        List<ProductVO> productVOList = new ArrayList<>();
        for (ProductCategory productCategory : productCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());

            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList) {
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return success(null, productVOList);
    }

}
